import {ref} from "vue"
import {storeToRefs} from "pinia"
import {useUserStore} from "@/stores/user.js"
import {loginApi} from "@/api/user.js"
import  {useRouter} from "vue-router"
import  Message  from "@/pulging/Message/js/Message.js"
/* 验证登录函数 */
export function useCheckLoginData () {
    const router = useRouter()
    const userStore = useUserStore()
    const {  saveAuthorization, saveUserInfo, outLogin} =userStore
    const {isLogin } = storeToRefs(userStore)
    /* 判断是否通过检查 */
    const isPass = ref(false)
    /* 验证登录数据 */
    function checkLoginData(user,hints) {
        hints.forEach((item) => {
            item.value.innerText = ''
        }
        )
        switch(true) {
            case user.account =='' :
                hints[0].value.innerText = '账号不能为空'
                break;
            case user.password =='' :
                hints[1].value.innerText = '密码不能为空'
                break;
            case user.checkCode =='' :
                hints[2].value.innerText = '验证码不能为空'
                break;
            default: 
                isPass.value = true;
                break;
        }
     }
     /* 登录功能 */
    function login (user, hintRefs){
        checkLoginData(user, hintRefs)
        if (!isPass.value) {
            return
        }
            loginApi(user)
            .then(res => {
                if (res.data.status == "LOGIN_SUCCESS") {
                        isLogin.value = true
                        saveAuthorization(res.headers.authorization)
                        saveUserInfo(res.data.data)
                        Message({type: "success", text: "登录成功"})
                        router.push("/home")
                    }else {
                        Message({type: "warn", text: res.data.message})
                    }
            })
            .catch((error) => {
                Message({type: "warn", text: "登录失败请重新登录"})
            })
    }
     return [isPass, checkLoginData,login]
}

